<%--
  Created by IntelliJ IDEA.
  User: 86150
  Date: 2020/8/13
  Time: 23:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!--360浏览器优先以webkit内核解析-->

    <title>商品详情</title>

    <link rel="shortcut icon" href="favicon.ico" />
    <link href="/css/bootstrap.min.css?v=3.3.7" rel="stylesheet" />
    <link href="/css/font-awesome.css?v=4.4.0" rel="stylesheet" />

    <link href="/css/plugins/awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css" rel="stylesheet">

    <link href="/css/plugins/simditor/simditor.css" rel="stylesheet" />

    <link href="/css/plugins/bootstrap3-editable/bootstrap-editable.css" rel="stylesheet">

    <link href="/js/plugins/webuploader/webuploader.css" rel="stylesheet">

    <link href="/css/animate.css" rel="stylesheet" />
    <link href="/css/style.css?v=4.1.0" rel="stylesheet" />
</head>

<body class="gray-bg">
<!-- 全局js -->
<script src="/js/jquery.min.js?v=2.1.4"></script>
<script src="/js/bootstrap.min.js?v=3.3.7"></script>

<!-- 自定义js -->
<script src="/js/content.js?v=1.0.0"></script>

<!-- jQuery Validation plugin javascript-->
<script src="/js/plugins/validate/jquery.validate.min.js"></script>
<script src="/js/plugins/validate/messages_zh.min.js"></script>

<!-- simditor -->
<script type="text/javascript" src="/js/plugins/simditor/module.js"></script>
<script type="text/javascript" src="/js/plugins/simditor/uploader.js"></script>
<script type="text/javascript" src="/js/plugins/simditor/hotkeys.js"></script>
<script type="text/javascript" src="/js/plugins/simditor/simditor.js"></script>

<!--bootstrap-editable -->
<script type="text/javascript" src="/js/plugins/bootstrap3-editable/bootstrap-editable.js"></script>

<!-- webuploader-->
<script type="text/javascript" src="/js/plugins/webuploader/webuploader.js"></script>

<div class="wrapper wrapper-content">
    <div class="row">
        <div class="pull-right">
            <c:if test="${detail != null}">
                <button id="goodsSave" type="button" class="btn btn-w-m btn-primary">保存并返回</button>
            </c:if>
            <c:if test="${detail == null}">
                <button id="goodsSave" type="button" class="btn btn-w-m btn-primary">新增并返回</button>
            </c:if>
            <button id="goodsCancel" type="button" class="btn btn-w-m btn-white">取消</button>
        </div>
    </div>
    <div class="row">
        <form class="form-horizontal m-t" id="goodsForm" method="post" action="/mgr/goods/edit">
            <div class="form-group">
                <label class="col-sm-3 control-label">商品名称：</label>
                <div class="col-sm-8">
                    <input id="goodsName" name="goodsName" value="${detail.goodsName}" class="form-control" type="text">
                    <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 请输入商品名称</span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">别名：</label>
                <div class="col-sm-8">
                    <input id="nickname" name="nickname" value="${detail.nickname}" class="form-control" type="text" aria-required="true" aria-invalid="false" class="valid">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">选择分类：</label>
                <div class="col-sm-8">
                    <select class="col-sm-3 form-control m-b" name="categoryFirst">

                    </select>
                    <select class="col-sm-3 form-control m-b" name="categorySecond">

                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">商品价格：</label>
                <div class="col-sm-8">
                    <table id="goodsPriceTable" class="table table-bordered">
                        <thead><tr><th>规格/单位</th><th>采购价（元）</th><th>零售价（元）</th><th>批发价（元）</th></tr></thead>
                        <tbody>
                        <c:if test="${detail != null}">
                            <c:forEach items="${detail.goodsPriceList}" var="goodsPrice">
                                <tr>
                                    <td><a href="#" name="unitName" data-id="${goodsPrice.priceId}">${goodsPrice.unitName}</a></td>
                                    <td><a href="#" name="buyPrice" data-id="${goodsPrice.priceId}">${goodsPrice.buyPrice/100.0}</a></td>
                                    <td><a href="#" name="retailPrice" data-id="${goodsPrice.priceId}">${goodsPrice.retailPrice/100.0}</a></td>
                                    <td><a href="#" name="wholesalePrice" data-id="${goodsPrice.priceId}">${goodsPrice.wholesalePrice/100.0}</a></td>
                                </tr>
                            </c:forEach>
                        </c:if>
                        <c:if test="${detail == null}">
                            <tr>
                                <td><a href="#" name="unitName"></a></td>
                                <td><a href="#" name="buyPrice"></a></td>
                                <td><a href="#" name="retailPrice"></a></td>
                                <td><a href="#" name="wholesalePrice"></a></td>
                            </tr>
                            <tr>
                                <td><a href="#" name="unitName"></a></td>
                                <td><a href="#" name="buyPrice"></a></td>
                                <td><a href="#" name="retailPrice"></a></td>
                                <td><a href="#" name="wholesalePrice"></a></td>
                            </tr>
                            <tr>
                                <td><a href="#" name="unitName"></a></td>
                                <td><a href="#" name="buyPrice"></a></td>
                                <td><a href="#" name="retailPrice"></a></td>
                                <td><a href="#" name="wholesalePrice"></a></td>
                            </tr>
                        </c:if>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">商品主图：</label>
                <div class="col-sm-8">
                    <input id="image" width="88px" height="88px" src="${detail.image}" onerror="this.src='/img/webuploader.png'" type="image">
                    <div style="width: 90px;margin-top:10px;" id="filePicker">
                        <i class="fa fa-upload"></i>&nbsp;&nbsp;<span class="bold">上传</span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">是否上架：</label>
                <div class="col-sm-8 col-md-4">
                    <div class="radio radio-info radio-inline">
                        <input type="radio" id="inlineRadio1" value="1" ${detail.isMarketable == 1 ? 'checked="checked"' : ''} name="isMarketable">
                        <label for="inlineRadio1"> 是 </label>
                    </div>
                    <div class="radio radio-info radio-inline">
                        <input type="radio" id="inlineRadio0" value="0" ${detail.isMarketable == 0 ? 'checked="checked"' : ''} name="isMarketable">
                        <label for="inlineRadio0"> 否 </label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">简要描述：</label>
                <div class="col-sm-8">
                    <textarea id="simpleDescribe" name="simpleDescribe" class="form-control">${detail.simpleDescribe}</textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">文章内容：</label>
                <div class="col-sm-8">
                    <textarea id="editor" name="detailDescribe" placeholder="这里输入内容">${detail.detailDescribe}</textarea>
                </div>
            </div>
            <input type="hidden" name="image" value="${detail.image}"/>
            <input type="hidden" name="goodsPriceListStr" value=""/>
            <input type="hidden" name="goodsCategoryStr" value=""/>
            <input type="hidden" name="goodsId" value="${detail.goodsId}"/>
        </form>
    </div>
</div>
<script type="application/javascript">
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        success: function (element) {
            element.closest('.form-group').removeClass('has-error').addClass('has-success');
        },
        errorElement: "span",
        errorPlacement: function (error, element) {
            if (element.is(":radio") || element.is(":checkbox")) {
                error.appendTo(element.parent().parent().parent());
            } else {
                error.appendTo(element.parent());
            }
        },
        errorClass: "help-block m-b-none",
        validClass: "help-block m-b-none"
    });

    //以下为官方示例
    $().ready(function () {

        // validate signup form on keyup and submit
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#signupForm").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2
                },
                password: {
                    required: true,
                    minlength: 5
                },
                confirm_password: {
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                },
                email: {
                    required: true,
                    email: true
                },
                topic: {
                    required: "#newsletter:checked",
                    minlength: 2
                },
                agree: "required"
            },
            messages: {
                firstname: icon + "请输入你的姓",
                lastname: icon + "请输入您的名字",
                username: {
                    required: icon + "请输入您的用户名",
                    minlength: icon + "用户名必须两个字符以上"
                },
                password: {
                    required: icon + "请输入您的密码",
                    minlength: icon + "密码必须5个字符以上"
                },
                confirm_password: {
                    required: icon + "请再次输入密码",
                    minlength: icon + "密码必须5个字符以上",
                    equalTo: icon + "两次输入的密码不一致"
                },
                email: icon + "请输入您的E-mail",
                agree: {
                    required: icon + "必须同意协议后才能注册",
                    element: '#agree-error'
                }
            }
        });

        // propose username by combining first- and lastname
        $("#username").focus(function () {
            var firstname = $("#firstname").val();
            var lastname = $("#lastname").val();
            if (firstname && lastname && !this.value) {
                this.value = firstname + "." + lastname;
            }
        });

        loanCatetory(0, $("select[name='categoryFirst']"));

        $("select[name='categoryFirst']").change(function(){
            var option = $(this).find("option:selected");
            var parentId = option.val();
            loanCatetory(parentId, $("select[name='categorySecond']"));
        });
    });

    function loanCatetory(parentId, _select) {
        $.ajax({
            //请求方式
            type : "POST",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url : "/goods/category/list?parentId=" + parentId,
            //数据，json字符串
            data : JSON.stringify({}),
            //请求成功
            success : function(result) {
                var fisrtId = ${detail.goodsCategory.firstId != null ? detail.goodsCategory.firstId : 0};
                var secondId = ${detail.goodsCategory.secondId != null ? detail.goodsCategory.secondId : 0};
                if (result.res == 1) {
                    _select.empty();
                    $.each(result.obj, function(index, item) {
                        if (parentId == 0) {
                            if (item.categoryId == fisrtId) {
                                _select.append("<option value=" + item.categoryId + " selected='selected'>" + item.categoryName + "</option>");
                                loanCatetory(fisrtId, $("select[name='categorySecond']"));
                            } else {
                                _select.append("<option value=" + item.categoryId + ">" + item.categoryName + "</option>");
                            }
                        } else {
                            if (item.categoryId == secondId) {
                                _select.append("<option value=" + item.categoryId + " selected='selected'>" + item.categoryName + "</option>");
                            } else {
                                _select.append("<option value=" + item.categoryId + ">" + item.categoryName + "</option>");
                            }
                        }
                    });
                }
            },
            //请求失败，包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    $(document).ready(function () {
        var editor = new Simditor({
            textarea: $('#editor')
        });
    });

    $.fn.editable.defaults.mode = 'popup';

    $(function () {
        $("a[name='unitName']").editable({
            type: 'text',
            validate: function(value) {

            },
            success:function (response, newValue) {
                // alert($(this).attr("data-id"));
            }
        });

        $("a[name='retailPrice']").editable({
            type: 'text',
            validate: function(value) {

            },
            success:function (response, newValue) {
                // alert($(this).attr("data-id"));
            }
        });

        $("a[name='buyPrice']").editable({
            type: 'text',
            validate: function(value) {

            },
            success:function (response, newValue) {
                // alert($(this).attr("data-id"));
            }
        });

        $("a[name='wholesalePrice']").editable({
            type: 'text',
            validate: function(value) {

            },
            success:function (response, newValue) {
                // alert($(this).attr("data-id"));
            }
        });

        $("#goodsCancel").click(function(){
            window.location.href = "/mgr/manage_goods_list.html";
        });

        $("#goodsSave").click(function(){

            var goodsPriceList = [];

            $("#goodsPriceTable tbody tr").each(function(index, item) {
                var unitNameItem = $(this).find("td").find("a[name='unitName']");
                var buyPriceItem = $(this).find("td").find("a[name='buyPrice']");
                var retailPriceItem = $(this).find("td").find("a[name='retailPrice']")
                var wholesalePriceItem = $(this).find("td").find("a[name='wholesalePrice']");
                if (unitNameItem.html() == 'Empty'
                    || buyPriceItem.html() == 'Empty'
                    || retailPriceItem.html() == 'Empty'
                    || wholesalePriceItem.html() == 'Empty') {
                    return;
                }
                goodsPriceList[index] = {};
                goodsPriceList[index].priceId = unitNameItem.attr("data-id");
                goodsPriceList[index].unitName = unitNameItem.html();
                goodsPriceList[index].buyPrice = buyPriceItem.html() * 100;
                goodsPriceList[index].retailPrice = retailPriceItem.html() * 100;
                goodsPriceList[index].wholesalePrice = wholesalePriceItem.html() * 100;
            });

            var goodsCategory = {};
            goodsCategory.firstId = $("select[name='categoryFirst']").find("option:selected").val();
            goodsCategory.secondId = $("select[name='categorySecond']").find("option:selected").val()

            // $("input[name='goodsPriceListStr']").val(encodeURI(JSON.stringify(goodsPriceList)));
            // $("input[name='goodsCategoryStr']").val(encodeURI(JSON.stringify(goodsCategory)));
            // $("#goodsForm").submit();

            var data = $("#goodsForm").serializeObject();
            data.categoryVo = goodsCategory;
            data.goodsPriceVoList = goodsPriceList;

            // ajax
            $.ajax({
                //请求方式
                type : "POST",
                //请求的媒体类型
                contentType: "application/json;charset=UTF-8",
                //请求地址
                url : '${detail == null ? "/mgr/goods/addAjax" : "/mgr/goods/editAjax"}',
                //数据，json字符串
                data : JSON.stringify(data),
                //请求成功
                success : function(result) {
                    if (result.res == 1) {
                        window.location.href =  "/mgr/manage_goods_list.html";
                    } else {
                        alert(result.obj);
                    }
                },
                error : function(errorCode, response) {

                }
            });

        });
    })

    $(function () {
        // 初始化Web Uploader
        var uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            innerHTML : "<i class=\"fa fa-upload\"></i>&nbsp;&nbsp;<span class=\"bold\">上传</span>",
            // swf文件路径
            swf: '/js/plugins/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: '/mgr/goods/img/upload',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#filePicker',
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });

        //
        uploader.on( 'fileQueued', function( file ) {
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $("#image").replaceWith('<span>不能预览</span>');
                    return;
                }
                $("#image").attr( 'src', src );
            }, 88, 88 );
        });

        uploader.on( 'uploadSuccess', function( file , response) {
            if (response.res == 1) {
                $("#image").attr('src', response.obj);
                $("input[name='image']").val(response.obj);
            }
        });

        uploader.on( 'uploadError', function( file , response) {
            alert("上传图片失败，请重新上传");
            uploader.cancelFile( file );
        });
    })
</script>
</body>
</html>
